package com.example.productserver.config;

import com.example.productserver.common.constant.RedisKeyPrefixConst;
import com.example.productserver.service.CyGoodsService;
import com.example.productserver.util.BloomFilterHelper;
import com.example.productserver.util.BloomRedisService;
import com.example.productserver.util.CollectionUtils;
import com.google.common.base.Charsets;
import com.google.common.hash.Funnel;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

@Configuration
public class BloomFilterConfig implements InitializingBean {
    @Autowired
    private CyGoodsService cyGoodsService;

    @Autowired
    private RedisTemplate redisTemplate;




    @Bean
    public BloomFilterHelper<String> initBloomFilterHelper() {
        return new BloomFilterHelper<>((Funnel<String>) (from, into) -> into.putString(from, Charsets.UTF_8)
                .putString(from, Charsets.UTF_8), 1000000, 0.01);
    }
    /**
     * 布隆过滤器bean注入
     * @return
     */
    @Bean
    public BloomRedisService bloomRedisService(){
        BloomRedisService bloomRedisService = new BloomRedisService();
        bloomRedisService.setBloomFilterHelper(initBloomFilterHelper());
        bloomRedisService.setRedisTemplate(redisTemplate);
        return bloomRedisService;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //加载所有商品
        List<Integer> pids = cyGoodsService.getAllCyGoodsIds().getData();
        if(CollectionUtils.isNotEmpty(pids)){
            pids.stream().forEach(pid->{
                bloomRedisService().addByBloomFilter(RedisKeyPrefixConst.PRODUCT_REDIS_BLOOM_FILTER,pid+"");
            });

        }

    }
}
